﻿#region

using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media.Imaging;

#endregion

namespace Radovici.Ctrls
{
    public class YouTubePicture : ContentControl
    {
        private const string DefaultVideo = "abcdefjklmn";

        public static readonly DependencyProperty YouTubeVideoProperty =
            DependencyProperty.Register("YouTubeVideo", typeof (string), typeof (YouTubePicture),
                                        new PropertyMetadata(DefaultVideo, onYouTubeVideoChanged));

        public string YouTubeVideo
        {
            get { return (string) GetValue(YouTubeVideoProperty); }
            set { SetValue(YouTubeVideoProperty, value); }
        }

        private static void onYouTubeVideoChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var pic = d as YouTubePicture;
            if (pic != null)
            {
                var tmpUrl = e.NewValue as string;
                if (!string.IsNullOrEmpty(tmpUrl))
                {
                    tmpUrl = tmpUrl.Replace("http://www.youtube.com/v/", string.Empty);
                }
                var img = new Image();
                var uri = new Uri(string.Format("http://i.ytimg.com/vi/{0}/1.jpg", tmpUrl ?? DefaultVideo));
                img.Source = new BitmapImage(uri);
                pic.Content = img;
            }
        }
    }
}